import * as path from 'node:path';

// https://github.com/sql-js/sql.js/issues/183
import sqlite from 'sqlite3';
import { Sequelize } from 'sequelize';
import { getAppPath } from '../utils';
import { initFilmMultimediaRelation } from './entities/filmMultimediaRelation';

// Get user's documents directory path
const APP_DIR = getAppPath()
const DB_FILE_PATH = path.join(APP_DIR, 'msg.db');

console.log('DB_FILE_PATH:', DB_FILE_PATH);

export const sequelize = new Sequelize({
  dialect: 'sqlite',
  dialectModule: sqlite,
  storage: DB_FILE_PATH,
  logging: console.log
});

// 初始化模型
initFilmMultimediaRelation(sequelize);

// 异步初始化和数据填充函数
async function initDb() {
  // 在这里进行模型的初始化和数据填充
}

(async () => {
  try {
    await sequelize.sync();
    console.log('Database connection has been established successfully.');
    await initDb();
  } catch (error) {
    console.error('Failed to sync database:', error);
    if (error instanceof Error) {
      console.error(error.stack);
    }
  }
})();

export default sequelize;
